package com.ikingtech.framework.sdk.base.model;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ikingtech.framework.sdk.utils.Tools;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * @author Tie Yan
 */
@Data
@Schema(name = "PageResult", description = "统一分页结果")
public class PageResult<T> {

    @Schema(name = "pages", description = "总页数")
    private long pages;

    @Schema(name = "total", description = "总条数")
    private long total;

    @Schema(name = "data", description = "查询到的数据")
    private List<T> data;

    public static <T> PageResult<T> build() {
        PageResult<T> result = new PageResult<>();
        result.setPages(0);
        result.setTotal(0);
        result.setData(new ArrayList<>());
        return result;
    }

    public static <T> PageResult<T> build(long pages, long total, List<T> data) {
        PageResult<T> result = new PageResult<>();
        result.setPages(pages);
        result.setTotal(total);
        result.setData(data);
        return result;
    }

    public static <T> PageResult<T> build(IPage<T> pageResult) {
        if (null == pageResult) {
            return build();
        }
        PageResult<T> result = new PageResult<>();
        result.setPages(pageResult.getPages());
        result.setTotal(pageResult.getTotal());
        result.setData(Tools.Coll.isBlank(pageResult.getRecords()) ? new ArrayList<>() : pageResult.getRecords());
        return result;
    }

    public <R> PageResult<R> convert(Function<T, R> converter) {
        if (Tools.Coll.isBlank(this.getData())) {
            return build();
        }
        PageResult<R> result = new PageResult<>();
        result.setPages(this.getPages());
        result.setTotal(this.getTotal());
        result.setData(Tools.Coll.convertList(this.getData(), converter));
        return result;
    }

    public <R> PageResult<R> convertBatch(Function<List<T>, List<R>> converter) {
        if (Tools.Coll.isBlank(this.getData())) {
            return build();
        }
        PageResult<R> result = new PageResult<>();
        result.setPages(this.getPages());
        result.setTotal(this.getTotal());
        result.setData(converter.apply(this.getData()));
        return result;
    }
}
